package com.wk.springboot.hwjs;

/**
 * description:
 * date 2021-01-10 11:12
 *
 * @author Administrator
 * @version 1.0
 */
public class Leetcode {

    public static void main(String[] args) {
        String s = "babad";
        Solution1 solution1 = new Solution1();
        String s1 = solution1.longestPalindrome(s);
        System.out.println("s1 = " + s1);
    }

    private static class Solution1 {
        public String longestPalindrome(String s) {
            int length = s.length();
            String hwsStart;
            String hwsEnd;
            String hwsStartEnd = null;
            int start = 0;
            int end = length;
            do {
                hwsStart = hws(s.substring(start));
                hwsEnd = hws(s.substring(0, end));
                if (start < end && hwsStartEnd == null)
                    hwsStartEnd = hws(s.substring(start, end));
                start++;
                end--;
            } while (hwsStart == null && hwsEnd == null && start < length);

            return getString(hwsStartEnd, hwsStart, hwsEnd);
        }

        private String getString(String... strings) {
            int max = 0;
            String string = null;
            for (int i = 0; i < strings.length; i++) {
                if(strings[i] == null){
                    continue;
                }
                int length = strings[i].length();
                if (length >= max) {
                    string = strings[i];
                    max = length;
                }
            }
            return string;
        }

        private String hws(String string) {
            StringBuffer stringBuffer = new StringBuffer(string);
            String s = stringBuffer.toString();
            String s1 = stringBuffer.reverse().toString();
            if (s.equals(s1)) {
                return s;
            }
            return null;
        }
    }
}
